const { ApolloServer, gql } = require('apollo-server-koa');
const BannerMongo = require("../mongodb/banner/index")

/**
 * 使用GraphQL模式语言构建模式
 * @type {}
 */
const typeDefs = gql`
  type Banner {
    title: String
    id: String
    pic: String
    detail: String
    switch: String
    index: Int
  }
  type Query {
    hello: String
    banners: [Banner]
  }
`;

/**
 * 为模式字段提供解析器函数
 * @type {{Query: {hello: (function(): string), banners(*, *, *=, *): Promise<*>}}}
 */
const resolvers = {
  Query: {
    hello: () => {
      return 'hello'
    },
    async banners(obj, args, context, info) {
      const dataArr = await BannerMongo.findAll()
      return dataArr
    }
  }
};

/**
 * 解析服务
 * @type {ApolloServer}
 */
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ctx}) => {
    // 将请求道的参数放到 context
    const reqParameter = ctx.request.method === 'GET' ? ctx.request.query : ctx.request.body
    return reqParameter
  },
  formatResponse: ({ data }) => {
    return {
      data,
      msg: '',
      code: 0
    }
  },
  formatError: (data) => {
    console.log(data)
    return '123'
  }
});

module.exports = function (app) {
  server.applyMiddleware({ app, path: '/graphql'});
}

// localhost:4000/graphql?query={banners{title id pic}}
